//
//  HSYQRReaderView.m
//  HSY
//
//  Created by 陈浩 on 2017/4/10.
//  Copyright © 2017年 金开门. All rights reserved.
//

#import "HSYQRReaderView.h"
#import <AVFoundation/AVFoundation.h>

@interface HSYQRReaderView ()<AVCaptureMetadataOutputObjectsDelegate>

@property (strong,nonatomic)AVCaptureDevice * device;
@property (strong,nonatomic)AVCaptureDeviceInput * input;
@property (strong,nonatomic)AVCaptureMetadataOutput * output;
@property (strong,nonatomic)AVCaptureSession * session;
@property (strong,nonatomic)AVCaptureVideoPreviewLayer * preview;

@property (nonatomic, assign) BOOL didSetup;

@end

@implementation HSYQRReaderView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setupAll];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        [self setupAll];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setupAll];
    }
    return self;
}

- (void)setupAll{
    if (self.didSetup) return;
    self.didSetup = YES;
    self.backgroundColor = [UIColor clearColor];
    // Device
    self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    // Input
    self.input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
    
    // Output
    self.output = [[AVCaptureMetadataOutput alloc]init];
    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    // Session
    self.session = [[AVCaptureSession alloc]init];
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    
    //连接输入和输出
    if ([_session canAddInput:self.input]){
        [_session addInput:self.input];
    }
    
    if ([_session canAddOutput:self.output]){
        [_session addOutput:self.output];
    }

    //设置条码类型
    _output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode128Code];
    
    //添加扫描画面
    self.preview =[AVCaptureVideoPreviewLayer layerWithSession:_session];
    _preview.videoGravity =AVLayerVideoGravityResizeAspectFill;
    _preview.frame =self.layer.bounds;
    [self.layer insertSublayer:_preview atIndex:0];
}

- (void)start{
    [_session startRunning];
}

- (void)stop{
    [_session stopRunning];
}


- (void)setRectOfInterest:(CGRect)rectOfInterest{
    _rectOfInterest = rectOfInterest;
    
    //坐标相反， x,y交换， w，h交换
    
    CGRect rect = CGRectMake(rectOfInterest.origin.y/CGRectGetHeight(self.frame), rectOfInterest.origin.x/CGRectGetWidth(self.frame), rectOfInterest.size.height/CGRectGetHeight(self.frame), rectOfInterest.size.width/CGRectGetWidth(self.frame));
    
    [_output setRectOfInterest:rect];
}

- (void)layoutSubviews{
    [super layoutSubviews];
    _preview.frame =self.layer.bounds;
}

#pragma mark - AVCaptureMetadataOutputObjectsDelegate -

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    NSString *stringValue;
    if ([metadataObjects count] >0){
        //停止扫描
        [_session stopRunning];
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
        stringValue = metadataObject.stringValue;
        
        if (self.delegate && [self.delegate respondsToSelector:@selector(readerView:didReadString:)]) {
            [self.delegate readerView:self didReadString:stringValue];
        }
    }
}



@end
